package cn.angis.system.config.satoken;

import cn.angis.system.model.Resource;
import cn.angis.system.service.ResourceService;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.solon.integration.SaTokenInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.route.RouterInterceptorChain;

import java.util.List;

/**
 * 鉴权
 *
 * @author angis.cn
 * @Date 2023/1/9 14:49
 */
public class AngisSaTokenPathInterceptor extends SaTokenInterceptor {

    private ResourceService resourceService;

    public AngisSaTokenPathInterceptor(){};
    public AngisSaTokenPathInterceptor(ResourceService resourceService) {
        this.resourceService = resourceService;
    }

    @Override
    public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
        super.doIntercept(ctx, mainHandler, chain);

        List<Resource> resourcesList = resourceService.getRouterList();
        for (Resource resource : resourcesList) {
            if (SaRouter.isMatch(resource.getRoutePath(), ctx.path()) && ctx.method().equalsIgnoreCase(resource.getHttpMethod())) {
                SaRouter.match(resource.getRoutePath(), () -> StpUtil.checkPermission(resource.getPermission()));
                break;
            }
        }
    }
}
